package com.shakespace.artofandroid.chapter03.conflict

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ListView

class ListViewEx @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    ListView(context, attrs, defStyleAttr) {


    private var lastX = 0
    private var lastY = 0

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {

        val eventX = ev.x.toInt()
        val eventY = ev.y.toInt()

        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                parent.requestDisallowInterceptTouchEvent(true)
            }

            MotionEvent.ACTION_MOVE -> {
                val deltaX = eventX - lastX
                val deltaY = eventY - lastY
                parent.requestDisallowInterceptTouchEvent(Math.abs(deltaX) > Math.abs(deltaY))
            }

            MotionEvent.ACTION_UP -> {
            }
            else -> {
            }
        }

        lastX = eventX
        lastY = eventY

        return super.dispatchTouchEvent(ev)
    }

}